package cn.ecnu.paper.service.impl;

import cn.ecnu.common.Constant;
import cn.ecnu.exception.RRXException;
import cn.ecnu.paper.mapper.AuthorMapper;
import cn.ecnu.paper.pojo.Author;
import cn.ecnu.paper.service.AuthorService;
import cn.ecnu.paper.vo.AuthorFrontVo;
import cn.ecnu.paper.vo.ViewAuthorVo;
import cn.ecnu.utils.PaginationUtil;
import cn.ecnu.vo.common.Pagination;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Service
public class AuthorServiceImpl implements AuthorService {

    @Resource
    private AuthorMapper authorMapper;

    @Override
    public ViewAuthorVo getAuthorAllList() {
        ViewAuthorVo vo = new ViewAuthorVo();
        List<Author> authors = authorMapper.getAllAuthors();
        vo.setAuthors(authors);
        return vo;
    }

    @Override
    public ViewAuthorVo getAuthorList(Integer pageNum) {
        int pageSize = 2;
        ViewAuthorVo vo = new ViewAuthorVo();
        int totalSize = authorMapper.getAuthorCount(); // 获取所有的totalSize

        Pagination pagination = PaginationUtil.paging(pageNum, totalSize, 2, "/author/list");
        vo.setPagination(pagination); // 获取对应的pagination
        pageNum = pagination.getCurrentPage();

        List<Author> authors = authorMapper.getAuthors((pageNum - 1) * pageSize, pageSize);
        vo.setAuthors(authors); // 获取所有的Authors
        return vo;
    }

    @Override
    public Author addAuthor(AuthorFrontVo vo) {
        if (vo.getAuthorName() == null) throw new RRXException(Constant.ARGUMENT_INVALID.getMsg(), Constant.ARGUMENT_INVALID.getCode());
        Author author = new Author();
        author.setAuthorName(vo.getAuthorName());
        authorMapper.addAuthor(author);
        return author;
    }
}
